package me.youline.dataServer.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import me.youline.dataServer.entity.UserDeviceToken;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component
public class UserDeviceTokenDAO {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	private static final String TABLE_NAME = "yline_base_userDeviceToken";

	private static final String INSERT_SQL = "insert into " + TABLE_NAME
			+ "(userId,deviceToken,updateTime)values(?,?,?)";

	private static final String UPDATE_SQL = "update " + TABLE_NAME
			+ " set deviceToken = ?,updateTime=? where userId = ? ";

	private static final String QUERY_SQL = "select * from " + TABLE_NAME
			+ " where userId = ? ";

	private static final String EVICT_DEVICETOKEN_SQL = "update " + TABLE_NAME
			+ " set deviceToken = ?  where userId = ? ";

	private static final RowMapper<UserDeviceToken> ROW_MAPPER = new RowMapper<UserDeviceToken>() {

		@Override
		public UserDeviceToken mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			UserDeviceToken token = new UserDeviceToken();
			token.setDeviceToken(rs.getString("deviceToken"));
			token.setUpdateTime(rs.getDate("updateTime"));
			token.setUserId(rs.getLong("userId"));
			return token;
		}
	};

	/**
	 * 增加用户的设备号记录
	 * 
	 * @param userDeviceToken
	 */
	public void addUserDeviceToken(UserDeviceToken userDeviceToken) {
		jdbcTemplate.update(
				INSERT_SQL,
				new Object[] { userDeviceToken.getUserId(),
						userDeviceToken.getDeviceToken(),
						userDeviceToken.getUpdateTime() });
	}

	/**
	 * 更新用户的设备号记录
	 * 
	 * @param userId
	 * @param deviceToken
	 */
	public int updateUserDeviceToken(Long userId, String deviceToken) {
		return jdbcTemplate.update(UPDATE_SQL, new Object[] { deviceToken, new Date(),
				userId });
	}

	/**
	 * 根据用户ID获取用户设备号
	 * 
	 * @param userId
	 * @return
	 */
	public UserDeviceToken getUserDeviceToken(Long userId) {
		try {
			return jdbcTemplate.queryForObject(QUERY_SQL,
					new Object[] { userId }, ROW_MAPPER);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	/**
	 * 将用户当前deviceToken作废
	 * 
	 * @param userId
	 */
	public void evictDeviceToken(Long userId) {
		jdbcTemplate.update(EVICT_DEVICETOKEN_SQL,
				new Object[] { null, userId });
	}
}
